<?php
namespace app\mobile\controller;

use app\model\Record; 
use app\model\Util; 
use app\model\Fee; 
use app\model\Comm; 
use app\model\Theme; 
use app\model\Poster; 
use app\model\Worker; 
use app\model\Fans; 
use app\model\Order; 
use app\model\Share; 
use app\model\Relation; 

class Index extends Base
{
    public function Index()
    {
global $_G, $_P;
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$fans = $this->checkuser();
$system=$_G['system'];
$themeid = intval($_P['themeid']);
if($themeid < 1){
	return_msg('活动入口不正确');
}

$theme = Theme::getThemeById($themeid);
if(empty($theme['id'])){
    die(Util::showError("请确认活动地址是否正确"));
    return;
}

$config = 	Theme::getConfig($themeid);
if (empty($config['bannerimgs']) && !empty($config['headlogo'])) {
	$config['bannerimgs'][0] =$config['headlogo'];
}

if ($config['maxcount']>0) {
$recordid = intval($_P['recordid']);
}
$record = Record::getAttendGroupByIdTuan($recordid);
if (!empty($record)){
	$recordid=$record['pid'];
}
if ($recordid>0) {//如果打开的团长是员工,强制清空
	$record = Record::getAttendGroupById($recordid);
	$myworker = Worker::getThemeWorkerByOpenid($record['openid'],$themeid,1);
	if (!empty($myworker)) {
		$recordid=0;
	}
}
if (TIMESTAMP > $theme['endtime']) {
	if(DOMAIN0 == "30.yixuan.net" ){
	    $theme['endtime']= TIMESTAMP+86400;;
		$theme['status']=1;		
	    db_update(t_theme, array("status"=>1,"endtime"=>$theme['endtime']), array('id' => $themeid));
	}else{
	    db_update(t_theme, array("status"=>2), array('id' => $themeid));
	    $theme['status'] = 2;		
	}
}

if (empty($system['endday'])) {
	$endday = 5;
}else{
	$endday = $system['endday'];
}
$endday = $endday*24*3600;

if ($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) {
	$recordid = 0;
	$config['musicsrc']="http://img2019.yixuansoft.cn/audios/2/2020/02/P30ZcCUDrmsCll9La3MNnAd36MRXS3.mp3";
	if ($system['s']['ishongbao']==1) {
		$system['fenxiao'] = 0;
		$config['iscomm'] = 0;
	}
	if ($system['s']['isfenxiao']==1) {
		$system['fenxiao01'] = 0;
		$config['danmu02'] = 1;
		$config['danmu03'] = 1;
	}
	if ($system['s']['iszhuanfa']==1) {
		$system['fenxiao04'] = 0;
		$config['danmu03'] = 1;
		$config['danmu04'] = 1;
	}
	if ($system['s']['isyaoyiyao']==1) {
		$system['fenxiao07'] = 0;
		$config['danmu03'] = 1;
		$config['danmu04'] = 1;
	}
	if ($system['s']['isticheng']==1) {
		$system['fenxiao06'] = 0;
	}
	if ($system['s']['isyuedu']==1) {
		$system['fenxiao05'] = 0;
	}
	if ($system['s']['isicon']==1) {
		$config['isicon'] = 0;
		$config['danmu01'] = 1;
	}
	if ($system['s']['isfanpai']==1) {
		$system['fanpai'] = 0;
	}
	if ($system['s']['isfujintuan']==1) {
		$config['isrecent'] = 0;
		$config['marketprice'] = '0.00';
	}	
	if ($system['s']['isjpeg']==1) {
		$config['headlogo']=str_replace(".jpeg",".jpg",$config['headlogo']);
	}
	if ($system['s']['istime']==1) {
		$config['istime']=10;
	}
	if ($system['s']['isheadimg']==1) {
		$config['iswttouxiang']=10;
	}
	if ($system['s']['isdanmu']==1) {
		$config['isdanmu']=0;
	}
}
if ($fans['status']==2){
	if ($system['s']['isbanquan']==1) {
		$theme['yixuanbanquan'] = 1;
	}
}
$cachekey = 'theme'.$_G['mpid'].MODULE_NAME.'-'.$themeid;

//未支付的进行较验是否已支付
Order::checkorder($themeid,$config,$system);


$workerid = intval($_P['workerid']);
$p = array(":themeid"=>$themeid);
$pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);


//如果已定单,客服为定单客服
$p3 = array(":uid"=>$_G['member']['uid'],":themeid"=>$themeid);
$recordinfo = db_find ( "SELECT * FROM " . tablename (t_record) . "
                                WHERE themeid =:themeid
                                        and uid = :uid and type<>8 order by id desc limit 1",$p3);
if ($config['joinfee']=='0.00' && $config['groupprice']=='0.00'){
	$recordid = 0;
	$themyrecord = $recordinfo;
	if ($config['touxiang']==2) {
		$config['touxiang']=1;
	}
}else{
    $themyrecord = Record::getLastGroupByUid($_G['member']['uid'],$themeid);
}

if(!empty($themyrecord)){
	if ($themyrecord['type']==1){
		$recordid = $themyrecord['pid'];
	}else{
		$recordid = $themyrecord['id'];
		$isleader = 1;
	}
	$themyrecordid = $recordid+10000;
}
if ($config['wuxian']==1) {
	$themyrecordid = "";
}
//员工信息
$isgetworker = false;
$myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
if(!empty($myworker) && $system['ruanjian']==3 && $config['showshop']!=$myworker['company'] && $config['showshop']>0){
	$isgetworker = true;
}
if (empty($myworker) || $isgetworker){
	if(!empty($themyrecord)){
		$workerid = $themyrecord['workerid'];
	}else{
		$workerid = intval($_P['workerid']);
	}
	if ($workerid==0){
		$relation = Relation::getByThemeId($themeid,$_G['openid']);
		$workerid = $relation['workerid'];
	}
	$totalTheme = Theme::getTotal("status <> '-1' ");
	if ($totalTheme>1) {
		if ($isgetworker){//如果是异业的复制员工信息
			if(!empty(Worker::getThemeWorkerByOpenidAlltheme($_G['openid'],1)) && empty($myworker)){
				Worker::CopyThemeWorkerByUid($_G['member']['uid'],$themeid,1);//复制员工信息到新活动
				if ($workerid != $_G['member']['uid']){
					$theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
				}
			}
		}else{
			if (empty($workerid)) {
				if(!empty(Worker::getThemeWorkerByOpenidAlltheme($_G['openid'],1))){
					$theyworker = Worker::CopyThemeWorkerByUid($_G['member']['uid'],$themeid,1);//复制员工信息到新活动
					$workerid = $_G['member']['uid'];
				}
			}elseif (!empty($workerid)){
				$theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
				if (empty($theyworker)){
					$theyworker = Worker::CopyThemeWorkerByUid($workerid,$themeid,1);//复制员工信息到新活动
				}
			}
		}	
	}elseif (!empty($workerid)){
		$theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
	}
	if ($isgetworker == false){
		$myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
	}else{
		$myworker = '';
	}
	if ($system['ruanjian']==3 && $config['showshop']>0 && $config['showshop']!=$theyworker['company'] ){
		$workerid = 0;
	}else{
		$workername = $theyworker['username'];
		$workermobile = $theyworker['mobile'];
		$company = $theyworker['company'];
		$workerqr = $theyworker['qrcode'];
        $workerposter = $theyworker['poster'];
	}
}else{

	$workerid = $myworker['uid'];
	$workername = $myworker['username'];
	$company = $myworker['company'];
	$workermobile = $myworker['mobile'];
	$workerqr = $myworker['qrcode'];
	$workerposter = $myworker['poster'];
	
	$sharedata = array(
	    'themeid'=>$themeid,
	    'fopenid'=>$_G['openid'],
	    'fromuid'=>$_G['member']['uid'],
	    'workerid'=>$workerid,
	);
	if (!empty($recordid)){
		$sharedata['recordid']=$recordid;
	}
	$workerurl =   $_G['siteroot'].createMobileUrl('index',$sharedata);
	//如果员工打开的链接为原始链接则先刷新
	if ($workerid != intval($_P['workerid'])){
		echo "<script language='javascript' type='text/javascript'>";
		echo "window.location.href='$workerurl';"; 
		echo "</script>";  
		exit;
	}
}


//如是打开不是自个的链接,记录打开的关系,并重新打开链接
if ($_G['member']['uid']!=$_P['fromuid'] ) {
	if ($system['friend']==1 || $config['isicon']==3 ) {
		if (!empty($_P['help_uid'])){
			$help_uid = $_P['help_uid'];
		}else{
			$help_uid = $_P['fromuid'];
		}
	}
	

    $fromuid = intval($_P['fromuid']);
    $fopenid = $_P['fopenid'];
    if($fromuid == $_G['member']['uid'] || $fopenid == $_G['openid']){
        $fromuid = 0;
        $fopenid = "";
    }elseif($workerid>0 && $fromuid==0){
        $theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
        $fromuid = $theyworker['uid'];
        $fopenid = $theyworker['openid'];
    }
    if($fromuid >0 && !empty($fopenid)){
    	//判断推荐者是不是员工
    	$isworker = Worker::getThemeWorkerByOpenid($fopenid,$themeid,1);
    	if (!empty($isworker)){
    		$workerid = $isworker['uid'];
    	}
        $relation = Relation::getByThemeId($themeid,$_G['openid']);
        $data = array(
            'themeid'   => $themeid,
            'uniacid'   => $_G['mpid'],
            'uid'       => $_G['member']['uid'],
            'openid'    => $_G['openid'],
            'status'    => 1,
            'addtime'   => TIMESTAMP,
            'parentid'  => $fromuid,
            'popenid'   => $fopenid,
        );
        if ($system['hdget']==1 && Fans::getuid_old($fromuid,$themeid)) {
            $data['parentid_old']  = $fromuid;
            $data['popenid_old']  = $fopenid;
        }
        if(empty($relation)){
            if ($system['hdget']==1 &&Fans::getuid_old($workerid,$themeid)) {
                $data['workerid_old']  = $workerid;
            }
            $data['workerid'] = $workerid;
            $insertid = db_insert(t_relation, $data);
        }elseif($relation['isorder']!=1){//如果没有付款则更新上下关系

            if($relation['popenid'] != $fopenid && $relation['isfrozen']!=1){
                Relation::update($relation['id'],$data);
            }
            if($relation['workerid'] != $workerid && $workerid > 0){
                if ($system['hdget']==1 &&Fans::getuid_old($workerid,$themeid)) {
                    Relation::update($relation['id'],array('workerid' => $workerid,'workerid_old' => $workerid));
                }else{
                    Relation::update($relation['id'],array('workerid' => $workerid));
                }
            }
        }
    }
    if($config['isyzmember']==1){
        $url = $_G['siteroot'] . 'addons/yun_shop/api.php?i='.$_G['mpid'].'&type=1&route=member.member.memberFromHXQModule';
        if($fromuid != $_G['member']['uid'] && $fopenid != $_G['openid']){
            //loadload_func('communication');
            $res = yxcurl($url, array('uid' =>$_G['member']['uid'],'mid' => $fromuid));
        }
    }

	$sharedata = array(
	    'themeid'=>$themeid,
	    'fopenid'=>$_G['openid'],
	    'fromuid'=>$_G['member']['uid'],
	    'workerid'=>$workerid,
	);
	if (!empty($recordid)){
		$sharedata['recordid']=$recordid;
	}
	if ($system['friend']==1 || $config['isicon']==3) {
		$sharedata['help_uid'] = $help_uid;
	}
	if($config['weixinh5']!=2){
		if ($fans['status']!=2) {
			$workerurl =   $_G['siteroot'].createMobileUrl('index',$sharedata);
			//如果员工打开的链接为原始链接则先刷新
			echo "<script language='javascript' type='text/javascript'>";
			echo "window.location.href='$workerurl';"; 
			echo "</script>";  
			exit;
		}
	}
}elseif ($system['friend']==1 || $config['isicon']==3) {
	if ($_P['help_uid']!=$_G['member']['uid']){
		if ($config['friendorder']==1){
			$help_uid = $_P['help_uid'];
		}else{
			$sql = "SELECT * FROM " . tablename (t_record) . "
								WHERE themeid =:themeid
										and uid = :uid and (status > 0 or status=-2) order by id desc limit 1";
			$isorder = db_find($sql, array(":themeid"=>$themeid,":uid"=>$_P['help_uid']));

			if (!empty($isorder) ){
				$help_uid = $_P['help_uid'];
			}
		}
	}
}


//更新浏览量

$pw = array(":workerid"=>$workerid);
db_query("UPDATE ".tablename(t_theme)." SET scansum = scansum +1 WHERE id =:themeid",$p);

db_query("UPDATE ".tablename(t_report)." SET scansum = scansum +1 WHERE software = '".MODULE_NAME."' and themeid =:themeid and riqi ='" . date("Y-m-d") ."'",$p);
db_query("UPDATE ".tablename(t_fans)." SET scansum = scansum +1 WHERE themeid =:themeid and openid = :openid",$pm);
db_query("UPDATE ".tablename(t_worker)." SET scansum = scansum +1 WHERE themeid = " . $themeid . " and uid =:workerid",$pw);
Theme::workerreport($themeid,$workerid,array('scansum' =>1));

$theme['scansum'] = $theme['scansum']+1;
//cache_write($cachekey, $theme);




	//参加人数
	if ($system['ruanjian']==0 && $system['softstyle']==5) {
		$total1 = Record::getNumByThemeId($themeid,$config['touxiang'],$config['showalldata']);
		
    	$tiaojian =" WHERE recordid=99999 ";
    	$sql = "SELECT * FROM " . tablename ( t_shengshi ) . " 
				  {$tiaojian} ORDER BY displayorder desc, areaId asc ";
		$list = db_select ( $sql );
		$total = db_fetchcolumn('SELECT COUNT(*) FROM ' .tablename(t_shengshi)."  {$tiaojian}");

	    $totalsum = $total1 + $config['fakejoin'] + $total;
	    $scannum = Record::getscannumByThemeId($themeid,$config['showalldata'])+intval($config['fakescan']);

	}elseif ($system['ruanjian']==3 && $system['softstyle']==2) {
		//参加人数
		$fanslist = Record::getFanslistByThemeIdall($themeid,$config['touxiang'],2000,$config['showalldata']);
		//隐藏客户真实姓名
		foreach ($fanslist as $index => $row){
			$usernamelen=mb_strlen($row['username'],'utf-8');
			if ($usernamelen > 2){
				$fanslist[$index]['username']=mb_substr($row['username'],0,1,'utf-8').'*'.mb_substr($row['username'],$usernamelen-1,1,'utf-8');
			}elseif (!empty($row['username'])){
				$fanslist[$index]['username']='*'.mb_substr($row['username'],-1,1,'utf-8');
			}

			$usernamelen=mb_strlen($row['mobile'],'utf-8');
			$fanslist[$index]['mobile']=mb_substr($row['mobile'],0,3,'utf-8').'****'.mb_substr($row['mobile'],$usernamelen-4,4,'utf-8');

        }
		$fanslisttop = Record::getFanslistByThemeIdall($themeid,$config['touxiang'],20,$config['showalldata']);

			foreach ($fanslisttop as $index => $row){
				
				$usernamelen=mb_strlen($row['mobile'],'utf-8');
				$fanslisttop[$index]['mobile']=mb_substr($row['mobile'],0,3,'utf-8').'****'.mb_substr($row['mobile'],$usernamelen-4,4,'utf-8');

	        }
		$total1 = Record::getNumByThemeId($themeid,$config['touxiang'],$config['showalldata']);
	    $totalsum = $total1 + $config['fakejoin'];
	}else{
		
	    $scannum = Record::getscannumByThemeId($themeid,$config['showalldata'])+intval($config['fakescan']);
			$total1 = Record::getNumByThemeId($themeid,$config['touxiang'],$config['showalldata']);
		    $totalsum = $total1 + $config['fakejoin'];
			if ($system['softstyle']==6){
				$txnum = 42;
			}else{
				$txnum = 105;
			}
			//参加人数
			if (!(($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) && $system['s']['istouxiang']==1)) {
				if ($system['softstyle']==6){
					$fanslist = Record::getFanslistByThemeIdjm($themeid,$config['touxiang'],$txnum);
				}else{
					$fanslist = Record::getFanslistByThemeId($themeid,$config['touxiang'],$txnum,$config['showalldata']);
				}
			}else{
				$fanslist= array();
			}
			//虚拟头像
			if (count($fanslist)<$txnum && $config['fakejoin']>0){
				$tempcount = $txnum-count($fanslist);
				if ($tempcount > $config['fakejoin']){
					$tempcount = $config['fakejoin'];
				}

				if (strstr($config['softtag0'],"婚纱")!==false ){
					$kaishishu = intval( substr(MODULE_NAME, -1))%10*20+700;
				}else{
					$kaishishu = intval( substr(MODULE_NAME, -1))%10*50;
				}
				if ($config['touxiang']==0){
					$xunisql = "SELECT nickname as username,avatar FROM " . tablename('2019xuni_fans') . " where
					 id >". $kaishishu ." limit ".$tempcount;
				}else{
					$xunisql = "SELECT username,avatar FROM " . tablename('2019xuni_fans') . " where
					 id >". $kaishishu ." limit ".$tempcount;
				}
				$xunilist = db_select ( $xunisql );
				$fanslist = array_merge($fanslist , $xunilist);
			}
			//隐藏客户真实姓名
			if ($config['touxiang']>0 && $config['isshowname']==1 ){
				foreach ($fanslist as $index => $row){
					$usernamelen=mb_strlen($row['username'],'utf-8');
					if ($usernamelen > 2){
						$fanslist[$index]['username']=mb_substr($row['username'],0,1,'utf-8').'*'.mb_substr($row['username'],$usernamelen-1,1,'utf-8');
					}elseif (!empty($row['username'])){
						$fanslist[$index]['username']='*'.mb_substr($row['username'],-1,1,'utf-8');
					}
			    }
			}
		}
	if (!empty($config['renshu'])){
		if($theme['status'] == 2 && $config['renshumode']==1){
			$totalsum = $config['renshu'];
		}
	}
	$numarray = str_split($totalsum.'');


    if (empty($config['nametext'])){
    	$config['nametext']='姓名';
    }
    if (empty($config['mobiletext'])){
    	$config['mobiletext']='手机号';
    }
	// $danmulist = array();
	// if($config['isreply'] == 1){
 //        $replysum = Reply::getNumByThemeIdAndStatus($themeid,1);
 //        $replylist =Reply::getListLimit20($themeid);
 //        $danmulist = $replylist;
	// }
	if($config['isicon'] > 0){
		if ($config['iconhang']!=0){
			$iconwidth=$config['iconhang'];
		}else{
			if ($config['iconnum']==3 || $config['iconnum']==2 ||$config['iconnum']==1){
				$iconwidth=28;
			}elseif ($config['iconnum']==4 || $config['iconnum']==7 ||$config['iconnum']==8){
				$iconwidth=21;
			}elseif ($config['iconnum']%5==0){
				$iconwidth=16;
			}elseif ($config['iconnum']%6==0 || $config['iconnum']%6==5 || $config['iconnum']%6==4 || $config['iconnum']%5==1 || $config['iconnum']%5==2){
				$iconwidth=12;
			}else{
				$iconwidth=16;
			}
		}
	}

	//查询是否是团员
    $mydetails = Record::getMyDetailList($_G['openid'],$themeid);
    if(!empty($mydetails)){
        foreach ($mydetails as $index =>$row){
            $mydetails[$index]['details'] = Record::getAttendDetailNumByPId($row['pid']);
        }
    }

	$isleader = 0;
	$isdetail = 0;
    $selfrecords = null;
	$showrecord = null;
	if($recordid > 0){//显示当前团信息
		$pr = $p;
		$pr[':id'] = $recordid;
		$record = Record::getAttendGroupById($recordid);
		if(!empty($record)){
            $showrecord = $record;
            if($record['openid'] == $_G['openid']){
                $isleader = 1;
            }else{
                $selfrecord = Record::getAttendGroupByOpenId($_G['openid'],$themeid);
                if(!empty($selfrecord)){
                    $selfrecord['details'] = Record::getAttendDetailNumByPId($selfrecord['id']);
                    $selfrecords[0] = $selfrecord;
                }
            }
        }else{
            $recordid = 0;
        }
	}
	

	if($recordid<=0){//查询是否自己是团长
		$myrecord = Record::getAttendGroupByOpenId($_G['openid'],$themeid);
		if(!empty($myrecord)){
			$showrecord = $myrecord;
			$isleader = 1;
		}
	}

	if($config['isgoon']==1){
        $selfrecords = Record::getAttendGroupListByOpenId($_G['openid'],$themeid);
        if(!empty($selfrecords)){
            foreach ($selfrecords as $index =>$row){
                $selfrecords[$index]['details'] = Record::getAttendDetailNumByPId($row['id']);
            }
        }
    }

		if(!empty($showrecord)){
	        $count = Record::getAttendDetailNumByPId($showrecord['id']);
			if($count > 0){
				$detaillist = Record::getDetailListByPid($showrecord['id']);
				foreach($detaillist as $index =>$row){
					if($row['openid'] == $_G['openid']){
						$isdetail = 1;
						break;
					}
				}
			} 

		    if ($showrecord['renshu'] == 1) {
		        $groupprice = $config['groupprice2'];
		        $maxcount = $config['maxcountall2']-1;
		        $maxcountall = $config['maxcountall2'];
		    }else{
		        $groupprice = $config['groupprice'];
		        $maxcount = $config['maxcount'];
		        $maxcountall = $config['maxcountall'];
		    }

			$nowgroupneednum=max(0,$maxcount-$count);

		    if ($showrecord['xunifinish']==1) {
		    	$kaishishu = $showrecord['uid'] % 500;
				$xunisql = "SELECT avatar,username FROM " . tablename('2019xuni_fans') . " where
					 id >". $kaishishu ." limit ".$nowgroupneednum;
				$xunilist = db_select ( $xunisql );
				if (!empty($detaillist)) {
					$detaillist = array_merge($detaillist , $xunilist);
				}else{
					$detaillist = $xunilist;
				}

		    	$nowgroupneednum=0;
		    }else{
				$num_arr = array();
				if ($config['maxcountall']<=20){
				  	for($i=0;$i<$nowgroupneednum;$i++){
				  		$num_arr[$i] = $i; 
				  	}
			  	}
		  	}
		}

	    if($config['iscomm']==1){
            //'发红包';
            if($system['autored']== 1 || $system['autored']==2){
                $totalpayfee = Order::getRealByThemeIdnew($themeid) + $theme['chongzhi'];
                if ($totalpayfee>1){
                    $row = Comm::getUnPayOneItemNew($system,$themeid);
                    if(!empty($row)){
                        Fee::commRecord($row,$system);
                    }
                }
            }
        }
	//发放进入就有红包
	if($config['hbopenfee1']>0 && $system['autored']==2){
		$ishbopen = Comm::addhbpoen($system,$config);
	}
	if(!($_G['companyname'] =='飞驰软件' && $system['softstyle']==0)){

		if($config['isrecent'] == 1){
			$recentlist = Record::getPayEdListByThemeIding($themeid,5);
			foreach ($recentlist as $index =>$row){
				if ($row['renshu'] == 1) {
		        	$neednum = $config['maxcountall2']-1;
				}else{
		        	$neednum = $config['maxcount'];
				}		

	            $details = Record::getAttendDetailNumByPId($row['id']);
	            $recentlist[$index]['details']  = $details;
	            $recentlist[$index]['neednum'] = $neednum;
	            $leftnum = $neednum-$details;
	            $recentlist[$index]['leftnum'] = $leftnum < 0?0:$leftnum;
	            if($neednum<= 0){
	                $neednum = 1;
	            }
	            $percent = round(floatval($details*100/$neednum),2);
	            $recentlist[$index]['percent']  = $percent;
	            
				if ($config['isshowname']==1 ){
					$usernamelen=mb_strlen($row['username'],'utf-8');
					if ($usernamelen > 2){
						$recentlist[$index]['username']=mb_substr($row['username'],0,1,'utf-8').'*'.mb_substr($row['username'],$usernamelen-1,1,'utf-8');
					}elseif (!empty($row['username'])){
						$recentlist[$index]['username']='*'.mb_substr($row['username'],-1,1,'utf-8');
					}
				}
	        }
		}
		if (!empty($config['renshu'])){
			$jindu = round(100*$totalsum/$config['renshu'],2);
			if($jindu > 100){
				$jindu = 100;
			}


			if ($config['renshumode']==1) {
				$jindu = 100-$jindu;
			}
			if ($config['renshumode']==1 || $config['renshumode']==2) {
				if ($totalsum>=$config['renshu']) {
				    db_update(t_theme, array("status"=>2), array('id' => $themeid));
				    $theme['status'] = 2;
				}
			}

			if (empty($config['renshutips'])) {
				if ($config['renshumode']==0 || $config['renshumode']==2) {
					$config['renshutips'] = "限量#renshu个名额，已报名#baoming人";
				}else{
					$config['renshutips'] = "限量#renshu个名额，还剩余#shengyu个名额";
				}
			}

			$shengyu = $config['renshu'] - $totalsum;
			if ($shengyu< 0 ){$shengyu = 0;}
			$config['renshutips'] = str_replace("#renshu", $config['renshu'], $config['renshutips']);
			$config['renshutips'] = str_replace("#baoming", $totalsum, $config['renshutips']);
			$config['renshutips'] = str_replace("#shengyu", $shengyu, $config['renshutips']);

		}
		
	    if($config['iscomm']==1){
			//屏蔽转发红包与摇一摇红包
			if($config['iscomm']==1 && ($system['fenxiao07']==1 || $config['comm41'] > 0) && !empty($workerid)){
				$theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);

				if (empty($theyworker) || $theyworker['comm4status']>1){
					$system['fenxiao07']=0;
					$config['comm41'] = 0;
				}
			}

		    //如果只开启了员工,前台不显示排行和图标
		    if ($system['fenxiao01'] >0 || $system['fenxiao04'] ==1 || $system['fenxiao05'] ==1 || $system['fenxiao07'] ==1){
		        $commssum = Comm::getcommssum($system,$themeid,$config['iscommshowfail']);
		        $commresult = Comm::getcommslist($system,$config,$themeid);
		        $commslist = $commresult['commslist'];
		        $commslisttoday = $commresult['commslisttoday'];
		        $fenxiaotip = $commresult['fenxiaotip'];
		    }
	    }
	}else{
		$commssum = Comm::getcommssum($system,$themeid,$config['iscommshowfail']);
	} 
	if($config['iscomm']==1 && $system['fenxiao07']==1){
		$commyaoyiyaofee = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
		WHERE themeid ='{$themeid}' and type = 7 and status  = 1 " ))); 

		$commyaoyiyao = db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_comm ) . "
		WHERE themeid ='{$themeid}' and type = 7 and status  = 1 " ); 
		$commyaoyiyao = $commyaoyiyao  + $config['comm7num'];
		$commyaoyiyaofee = sprintf("%.2f",$commyaoyiyaofee  + $config['comm7fee']);

	}
    $poster = Poster::getByThemeIdnew($themeid);
    if(!empty($poster['bg'])){
        $waittips = empty($poster['waittips'])?'正在生成海报':$poster['waittips'];
        $config['isposter']=1;
		if ($fans['status']==2 && $system['s']['istubiao']==1) {
			$config['isposter']=0;
		}

		$myposter = db_find("SELECT * FROM ".tablename(t_fans)."
			WHERE themeid = :themeid and openid = :openid",$pm);
    }

    //显示二维码
	$showewm = 0;
	if($system['isfollow']==1 && $_G['member']['follow']==0){
		$showewm = 1;
	}


	if (intval($config['groupneedtime'])>0){
        $refundtime=strtotime('+'.intval($config['groupneedtime']).' hour',$showrecord['addtime']);
        //echo date("Y-m-d H:i:s",$refundtime);
    }else{
        $refundtime=0;
    }
    if ($config['wuxian']==1) {
		$showrecord = "";
	}

   	//异业联盟的读取商家信息
    if($system['ruanjian']==3 && $config['showshop']==0){
		$grouplist = db_select ( "SELECT * FROM " . tablename (t_shangjiagroup) .
				"  order by displayorder" );

    	$shoptiaojian="";
    	if (!empty($company)) {
			$myshop = db_find ( "SELECT * FROM " . tablename (t_shangjia) .
				" WHERE  id = '{$company}' and state = 1 order by displayorder" );
			if ($system['softstyle']!=6) {
				if ($config['homeshowshop']==0) {
					$shoptiaojian=" and id <> '" . $company ."' ";
				}else{
					$shoptiaojian=" and w.company <> '" . $company ."' ";
				}
			}
			$shopname = $myshop['name'];
    	}
	    	
		if (!empty($grouplist) && $system['softstyle']!=0){
			foreach ($grouplist as $index => $item) {
				$shoplist = db_select ( "SELECT * FROM " . tablename (t_shangjia) .
					" WHERE  groupid ='{$item['id']}'  and state = 1 order by displayorder" );
				$grouplist[$index]['shoplist']=$shoplist;
			}
		}else{
			if ($config['homeshowshop']==0) {
				$shoplist = db_select ( "SELECT * FROM " . tablename (t_shangjia) .
					" WHERE  1=1 {$shoptiaojian} and state = 1 order by displayorder" );
			} else {
				$shoplist = db_select("SELECT sum(r.record) as record,s.* FROM " . tablename ( t_worker ) . " w
	left join " . tablename ( t_shangjia ) . " s on w.company = s.id
	left join " . tablename ( t_workerreport ) . " r on w.uid = r.workerid and w.themeid = r.themeid
	WHERE 1=1 {$shoptiaojian} group by w.company order by record desc,s.displayorder,s.id" );
			}
			


			$grouplist[0]['img']= $_G['URL']['DUOSHANGJIA_CSS'] . 'images/free.png';
			$grouplist[0]['name']='免费详情';
			$grouplist[0]['shoplist']=$shoplist;
		}

		$logolist = db_select ( "SELECT * FROM " . tablename (t_shangjia) .
					" WHERE  state = 1 and logo<>'' order by displayorder" );

		$xunichengjiao = intval(db_fetchcolumn ( 'SELECT sum(xunichengjiao) FROM ' . tablename ( t_shangjia ) . "
				WHERE state = 1 " ));
		$totalsum = $totalsum + $xunichengjiao;
    }


	if( $config['isdanmu'] > 0 && $theme['endtime'] > TIMESTAMP && $theme['status'] == 1){
		$imgur = "https://css2019.yixuan.net/headimgs/2" . intval( substr(MODULE_NAME, -1))%5;

		$danmulist = array();
		if ($system['softstyle']!=5) {
			$limitNum=30;
			if($config['iscomm']==1){
				$commlist = Comm::getListByThemeIdNew($themeid,$limitNum,$config['danmu02'],$config['danmu03'],$config['danmu04']);
			    if(!empty($commlist)){
		            foreach ($commlist as $index => $row){
		            	$row['nickname']=str_replace("'","",$row['nickname']);
		            	if (($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) && $system['s']['istouxiang']==1) {
		            		$row['avatar'] = $imgur .  substr($row['fansuid'], -2) . ".jpg";
		            	}
				    	$data = array(
							'nickname'  => mb_substr($row['nickname'],0,5,'utf-8'),
							'img'    	=> $row['avatar'],
							'info'  	=> ' &#21018;&#21018;&#33719;&#24471;&#32418;&#21253;'.$row['fee'].'元',
							);
				    	$danmulist[] = $data;
		            }
		        }
		    }
		   //  if($config['isreply'] == 1){
		   //      $replylist =Reply::getListLimit20($themeid);
		   //      if (!empty($replylist)){
				 //    foreach ($replylist as $index => $row){
				 //    	$row['nickname']=str_replace("'","",$row['nickname']);
				 //    	$data = array(
					// 		'nickname'  => mb_substr($row['nickname'],0,5,'utf-8'),
					// 		'img'    	=> $row['avatar'],
					// 		'info'  	=> ' 说:'.$row['content'],
					// 		);
				 //    	$danmulist[] = $data;
					// }
		   //      }
		   //  }
		    if($config['isicon'] > 0 && $config['iconnum2'] == 0 && $config['danmu01']==0){
		        $slist =Share::getListByThemeId($themeid,5);
		        if (!empty($slist)){
					foreach ($slist as $index => $row){
						$row['nickname']=str_replace("'","",$row['nickname']);
		            	if (($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) && $system['s']['istouxiang']==1) {
		            		$row['avatar'] = $imgur .  substr($row['fansuid'], -2) . ".jpg";
		            	}
				    	$data = array(
							'nickname'  => mb_substr($row['nickname'],0,5,'utf-8'),
							'img'    	=> $row['avatar'],
							'info'  	=> ' &#21018;&#21018;&#28857;&#20142;&#49;&#39063;&#22270;&#26631;',
							);
				    	$danmulist[] = $data;
					}
				}
		    }
		    $glist = Record::getLimitByIdnew($themeid,$limitNum);
		    if (!empty($glist)){
				foreach ($glist as $index => $row){
					if($row['type'] == 0){
						if ($system['ruanjian']==1 || $system['softstyle']==7 || $config['maxcountall']<2) {
							$row['content'] = ' &#21018;&#21018;&#25104;&#21151;&#25253;&#21517;';
						}else{
							$row['content'] = ' &#21018;&#21018;&#25104;&#21151;&#25250;&#36141;';
						}
					}if($row['type'] == 1){
						$row['content'] = ' &#21018;&#21018;&#25104;&#21151;&#25250;&#36141;';
					}if($row['type'] == 9){
						$row['content'] = ' &#21018;&#21018;&#25104;&#21151;&#25250;&#36141;';
					}
					$row['nickname']=str_replace("'","",$row['nickname']);
	            	if (($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) && $system['s']['istouxiang']==1) {
	            		$row['avatar'] = $imgur .  substr($row['fansuid'], -2) . ".jpg";
	            	}
			    	$data = array(
						'nickname'   => mb_substr($row['nickname'],0,5,'utf-8'),
						'img'    => $row['avatar'],
						'info'  => $row['content'],
						);
			    	$danmulist[] = $data;
				}
		    }
		}else{
			$limitNum=30;
			if($config['iscomm']==1){
				$commlist = Comm::getListByThemeIdNew($themeid,$limitNum,$config['danmu02'],$config['danmu03'],$config['danmu04']);
			    if(!empty($commlist)){
		            foreach ($commlist as $index => $row){
		            	$row['nickname']=str_replace("'","",$row['nickname']);
		            	if (($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) && $system['s']['istouxiang']==1) {
		            		$row['avatar'] = $imgur .  substr($row['fansuid'], -2) . ".jpg";
		            	}
				    	$data = array(
							'nickname'  => mb_substr($row['nickname'],0,5,'utf-8'),
							'img'    	=> $row['avatar'],
							'info'  	=> '&#21018;&#21018;&#33719;&#24471;&#32418;&#21253;'.$row['fee'].'元',
							);
				    	$danmulist[] = $data;
		            }
		        }
		    }
		    $glist = Record::getLimitByIdnew($themeid,$limitNum);
		    if (!empty($glist)){
				foreach ($glist as $index => $row){
					if($row['type'] == 0){
						$row['content'] = ' &#21018;&#21018;&#25104;&#21151;&#21152;&#30431;';
					}if($row['type'] == 1){
						$row['content'] = ' &#21018;&#21018;&#25250;&#36141;&#25104;&#21151;';
					}if($row['type'] == 9){
						$row['content'] = ' &#21018;&#21018;&#25250;&#36141;&#25104;&#21151;';
					}
					$row['nickname']=str_replace("'","",$row['nickname']);
	            	if (($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) && $system['s']['istouxiang']==1) {
	            		$row['avatar'] = $imgur .  substr($row['fansuid'], -2) . ".jpg";
	            	}
			    	$data = array(
						'nickname'   => mb_substr($row['nickname'],0,5,'utf-8'),
						'img'    => $row['avatar'],
						'info'  => $row['content'],
						);
			    	$danmulist[] = $data;
				}
		    }
		}
	    shuffle($danmulist);
	    $danmulisttop = $danmulist;
	    shuffle($danmulist);
	}
	if ($system['gift']==1) {
		if (empty($themyrecord)){
			$sql = "SELECT * FROM " . tablename ( t_gift ) . " 
										WHERE giftgroupid = '{$config['giftgroupid']}' and state=1 ORDER BY displayorder ";
			$giftlist = db_select ( $sql );
		}elseif(!empty($themyrecord['giftids'])){
			$ids = unserialize($themyrecord['giftids']);
			$idsstr = "";
			foreach ($ids as $index => $id){
				if($index == 0){
					$idsstr.= "(".$id;
				}else{
					$idsstr.= ",".$id;
				}
			}
			$idsstr.=")";
			$giftsql = "SELECT * FROM " . tablename ( t_gift ) . " WHERE id in {$idsstr} ORDER BY displayorder ";
			$hasgiftlist = db_select ( $giftsql );
			$hasgiftlcount = count($hasgiftlist);
			$jiaz = db_find ( "SELECT sum(giftjiazhi) as cnt FROM " . tablename ( t_gift ) . " WHERE id in {$idsstr}" );
			$jiazsum = $jiaz ['cnt'] <= 0 ? 0 : $jiaz ['cnt'];
		}
	}

	//邀请助力 送星星
	if ($config['isicon']==3) {
		if (!empty($help_uid)){
			$friendlistuid = $help_uid;
		}elseif (!empty($themyrecord) || $config['friendorder']==1){
			$friendlistuid = $_G['member']['uid'];
		}
	}
	if ($system['friend']==1) {
		if (!empty($help_uid)){
			$friendlistuid = $help_uid;
		}elseif (!empty($themyrecord) || $config['friendorder']==1){
			$friendlistuid = $_G['member']['uid'];
		}
		if (!empty($friendlistuid)){
			$friendfans = Fans::getById($friendlistuid,$themeid);
			$friendshengyu = $friendfans['friendnum']-$friendfans['friendshiyong'];
		}else{
			$friendshengyu = 0;
		}
		// if (!empty($friendlistuid)){

		// 	$friendfans = Fans::getById($friendlistuid,$themeid);
		// 	$params = array();
		//     
		//     $params[':uid'] = $_G['member']['uid'];
		//     $params[':fromuid'] = $help_uid;
		//     $params[':themeid'] = $themeid;
		//     $friend = db_find("SELECT * FROM ".tablename(t_friend)."
		// 		WHERE uid = :uid and themeid = :themeid and fromuid = :fromuid",$params);

		// 	if(empty($friend)){
		// 		$isfriend = 0;
		// 	}else{
		// 		$isfriend = 1;
		// 	}

		//     $params = array();
		//     
		//     $params[':fromuid'] = $friendlistuid;
		//     $params[':themeid'] = $themeid;

		// 	$friendlist = db_select("SELECT * FROM ".tablename(t_friend)."
		// WHERE themeid = :themeid and fromuid = :fromuid",$params);
		// 	$friendshengyu = $friendfans['friendnum']-$friendfans['friendshiyong'];

		// }else{
		// 	$friendshengyu = 0;
		// }

		// 	$sql = "SELECT * FROM " . tablename ( t_gift ) . " 
		// 								WHERE giftgroupid = '{$config['friend_groupid']}' ORDER BY displayorder ";
		// 	$friendlipinlist = db_select ( $sql );
		
		// 	foreach ($friendlipinlist as $index => $item) {
		// 		if ($friendshengyu>=$item['duihuan']){
		// 			$friendlipinlist[$index]['jindu'] = 100;
		// 		}else{
		// 			$friendlipinlist[$index]['jindu'] = intval($friendshengyu/$item['duihuan']*100);
		// 		}
		// 		// if ($friendlistuid == $_G['member']['uid']){
		// 			$params = array();
		// 		    
		// 		    $params[':uid'] = $friendlistuid;
		// 		    $params[':giftid'] = $item['id'];
		// 		    $params[':themeid'] = $themeid;
		// 		    $isduihuan = db_find("SELECT * FROM ".tablename(t_exchange)."
		// 				WHERE uid = :uid and themeid = :themeid and giftid = :giftid",$params);
		// 		    if (!empty($isduihuan)){
		// 				$friendlipinlist[$index]['isduihuan'] = 1;
		// 			}
		// 		// }

		// 	}
	}


	//按扭文字替换通配符
	// if ($config['joinfee']=='0.00'){
	// 	if (empty($config['formtextcenter'])){
	// 		$config['formtextcenter']="发起拼团";
	// 		$config['isshowprice']=2;
	// 	}
	// 	if (empty($config['formtextcenternew'])) {
	// 		$config['formtextcenternew']="我要开团";
	// 		$config['isshowprice']=2;
	// 	}
	// 	if (empty($config['formtextright'])) {
	// 		$config['formtextright']="加入TA的团";
	// 		$config['isshowprice']=2;
	// 	}
	// }else{
	// 	if (empty($config['formtextcenter'])) {
	// 		$config['formtextcenter']="￥#fee#br发起拼团";
	// 		$config['isshowprice']=1;	
	// 	}
	// 	if (empty($config['formtextcenternew'])) {
	// 		$config['formtextcenternew']="￥#fee#br我要开团";
	// 		$config['isshowprice']=1;	
	// 	}
	// 	if (empty($config['formtextright'])) {
	// 		$config['formtextright']="￥#fee#br加入TA的团";
	// 		$config['isshowprice']=1;	
	// 	}
	// }
	// if ($config['groupprice2']>0){
	// 	if ($config['formtextcenter']=="￥#fee#br发起拼团" || $config['formtextcenter']=="发起拼团") {
	// 		$config['formtextcenter']="￥#tuan#br".$config['maxcountall']."人团";
	// 		$config['isshowprice']=1;	
	// 	}
	// 	if (empty($config['formtextcenter2'])) {
	// 		$config['formtextcenter2']="￥#tuan#br".$config['maxcountall2']."人团";
	// 		$config['formtextright']="￥#fee#br加入TA的团";
	// 		$config['isshowprice']=1;
	// 	}
	// }

	$formtextpay = Theme::ButtonTextReplace($config['formtextpay'],$config['joinfee'],$config['primeprice'],$config['groupprice']);

	if ($system['jiage'] > 0){ 
		$formtextpay = '立即支付';
		$formtextpay1 = Theme::ButtonTextReplace($config['formtextpay'],$config['joinfee'],0,0);
		$formtextpay2 = Theme::ButtonTextReplace($config['formtextpay'],$config['joinfee2'],0,0);
		$formtextpay3 = Theme::ButtonTextReplace($config['formtextpay'],$config['joinfee3'],0,0);
		$config['formtextcenter']= str_replace("￥#fee#br", "", $config['formtextcenter']);
		$config['formtextcenter2']= str_replace("￥#fee#br", "", $config['formtextcenter2']);
		$config['formtextcenternew']= str_replace("￥#fee#br", "", $config['formtextcenternew']);
		$config['formtextright']= str_replace("￥#fee#br", "", $config['formtextright']);
		$config['formtextleft']= str_replace("￥#fee#br", "", $config['formtextleft']);
		$config['isshowprice']=0;
	}
	 
	$formtextleft = Theme::ButtonTextReplace($config['formtextleft'],$config['joinfee'],$config['primeprice'],$config['groupprice']);
	$formtextcenter = Theme::ButtonTextReplace($config['formtextcenter'],$config['joinfee'],$config['primeprice'],$config['groupprice']);
	$formtextcenter2 = Theme::ButtonTextReplace($config['formtextcenter2'],$config['joinfee'],$config['primeprice'],$config['groupprice2']);
	$formtextcenternew = Theme::ButtonTextReplace($config['formtextcenternew'],$config['joinfee'],$config['primeprice'],$config['groupprice']);
	$formtextright = Theme::ButtonTextReplace($config['formtextright'],$config['joinfee'],$config['primeprice'],$groupprice);

		$wtformtextpay = Theme::ButtonTextReplace($config['wtformtextpay'],$config['joinfee'],$config['primeprice'],$config['groupprice']);	
		$wtformtextleft = Theme::ButtonTextReplace($config['wtformtextleft'],$config['joinfee'],$config['primeprice'],$config['groupprice']);
	if ($system['softstyle']==5) {
		$jmdibuwenzi = Theme::ButtonTextReplace($config['jmdibuwenzi'],$config['joinfee'],$config['primeprice'],$config['groupprice']);
		$jmzhifuwenzi = Theme::ButtonTextReplace($config['jmzhifuwenzi'],$config['joinfee'],$config['primeprice'],$config['groupprice']);
		$jmzhifuwenzi2 = Theme::ButtonTextReplace($config['jmzhifuwenzi2'],$config['joinfee'],$config['primeprice'],$config['groupprice']);

		$jmzhifuwenzi = str_replace("<em>", "", $jmzhifuwenzi);
		$jmzhifuwenzi = str_replace("</em>", "", $jmzhifuwenzi);
		$jmzhifuwenzi2 = str_replace("<em>", "", $jmzhifuwenzi2);
		$jmzhifuwenzi2 = str_replace("</em>", "", $jmzhifuwenzi2);
	}
	//加盟系统
	if ($system['softstyle']==5) {
		$sql = "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE parentId= -1 ORDER BY displayorder desc, areaId asc";
		$shenglist = db_select ( $sql );
		foreach ($shenglist as $shengindex => $sheng) {
			$sql = "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE parentId= " . $sheng['areaId'] . " ORDER BY displayorder desc, areaId asc";
			$shilist = db_select ( $sql );
			$shenglist[$shengindex]['shilist']=$shilist;
			foreach ($shilist as $shiindex => $shi) {
				$sql = "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE parentId= " . $shi['areaId'] . " ORDER BY displayorder desc, areaId asc";
				$xianlist = db_select ( $sql );
				$shenglist[$shengindex]['shilist'][$shiindex]['xianlist']=$xianlist;
			}
		}
		if (!empty($themyrecord)){
			$item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $themyrecord['address']);
			$shengshi = $item['areaName'];
			if (!empty($item)) {
				$item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $item['parentId']);
				$shengshi = $item['areaName'] . $shengshi;
			}
			if (!empty($item)) {
				$item = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $item['parentId']);
				$shengshi = $item['areaName'] . $shengshi;
			}
		}
	}
	
	//二维码空缺自动补发
	if ($system['qrlist']==1 && $config['qrlistbufa']==0 && !empty($themyrecord) && empty($themyrecord['qrimg']) ) {		
		if ($config['qrlistmode']==0 || ($config['qrlistmode']==1 && $themyrecord['isfinish']==1)) {
	        $sql = "SELECT * FROM " . tablename ( t_qrlist ) . " 
	            WHERE themeid = '{$themeid}' and state = 1 and usercount<qrnum ORDER BY displayorder asc, id asc ";
	        $list = db_find ( $sql);
	        if (!empty($list)) {
	            db_run('set AUTOCOMMIT=0');//关闭自动提交，自此句执行以后，每个SQL语句或者语句块所在的事务都需要显示"commit"才能提交事务
	            db_run('START TRANSACTION');//启动一个新事务
	            $qrliststate = db_query("UPDATE ".tablename(t_qrlist)." SET usercount = usercount+1 WHERE id =".$list['id']);
	            $recordstate = db_query("UPDATE ".tablename(t_record)." SET qrimgid = '". $list['id'] ."',qrimg ='" .$list['qrimg']."' WHERE id = ".$themyrecord['id'] );
	            $themyrecord['qrimg'] = $list['qrimg'];
	            if (!$qrliststate || !$recordstate) {
	                db_run('ROLLBACK');//事务回滚
	            }else{
	                db_run('COMMIT');//事务提交
	            }

	        }
        }
	}
 
	//抽奖：未报名的客户获得抽奖机会
	if ($system['fanpai']==1 && $config['fanpaigroupid']>0) {
		$sql = "SELECT * FROM " . tablename ( t_gift ) . " 
									WHERE giftgroupid = '{$config['fanpaigroupid']}' and state=1 ORDER BY displayorder ";
		$fanpailist = db_select ( $sql );
		if (count($fanpailist)<1){
			return_msg('抽奖礼品未设置！');
		}
		if ($config['fanpailimit'] > count($fanpailist)){
			return_msg('抽奖礼品设置错误：礼品数小于抽奖上限！');
		}
		if ($config['fanpaiweibaoming'] > 0){
			$sql = "SELECT * FROM " . tablename ( t_fanpaijihui ) . " WHERE themeid= " . $themeid . " and  uid= " . $_G['member']['uid'] . " and type = 0";
			$jihuilist = db_select ( $sql );
			if (empty($jihuilist)){
		        $tempdata = array(
		            'themeid'   => $themeid,
		            'uniacid'   => $_G['mpid'],
		            'uid'       => $_G['member']['uid'],
		            'openid'    => $_G['openid'],
		            'nickname'  => $fans['nickname'],
		            'avatar'    => $fans['avatar'],
		            'status'    => 0,
		            'type'    => 0,
		            'jihui'    => $config['fanpaiweibaoming'],
		            'addtime'   => TIMESTAMP,
		            'workerid' => $workerid,
		        );
			    if ($system['hdget']==1 &&Fans::getuid_old($workerid,$themeid)) {
			        $data['workerid_old']  = $workerid;
			    }
				$insertid = db_insert(t_fanpaijihui, $tempdata);
				db_query("UPDATE ".tablename(t_fans)." SET jihui = jihui + " . $config['fanpaiweibaoming'] . " WHERE themeid =:themeid and openid = :openid",$pm);
			}
		}

		$pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);
		$yichou = db_fetchcolumn("SELECT COUNT(*)  FROM ".tablename(t_fanpaichoujiang)."
		WHERE themeid = :themeid and openid = :openid",$pm);

		$jihui = $config['fanpailimit']- $yichou;

		$jihui =  ($jihui>$fans['jihui']) ? $fans['jihui'] : $jihui ;

		if ($yichou>0) {
			foreach ($fanpailist as $index => $row) {
				$choujianglist = db_find("SELECT * FROM ".tablename(t_fanpaichoujiang)."
				WHERE uid = :uid and themeid =:themeid and weizhi =:weizhi",array(":themeid"=>$themeid,":uid"=>$_G['member']['uid'],":weizhi"=>$index));
				if(!empty($choujianglist )){
					$fanpailist[$index]['newgift']=$choujianglist['giftimg'];
				}
			}
		}
		if ($config['fanpaijilu']==0) {
			$fanpaijilu = db_select("SELECT c.*,f.mobile FROM ".tablename(t_fanpaichoujiang)." as c
				left join ".tablename(t_fans)." as f on c.uid = f.uid
				WHERE f.themeid =:themeid and giftname<>'未中奖' order by c.id desc limit 20",array(":themeid"=>$themeid));
		}


	}
	if ($config['shopstype'] == 4) {
		if (!empty($config['gudingoptions'])) {
			$guding = count($config['gudingoptions']);
		} else {
			$guding = 0;
		}
	}
	if ($config['tuanrank'] > 0){
	    $tuannum = Record::getFansNumByThemeId($themeid,$config['showalldata']);
	    // $groupsnum = intval($groupsnum)+intval($config['faketuan']);;

		$tuanranklist = db_select("SELECT * FROM ".tablename(t_record)."
                            WHERE themeid =" . $themeid ." and status > 0 and type = 0 ORDER BY tuannum desc,addtime desc limit " . $config['tuanrank']);
		foreach ($tuanranklist as $index => $row) {
			$usernamelen=mb_strlen($row['username'],'utf-8');
			if ($usernamelen > 2){
				$tuanranklist[$index]['username']=mb_substr($row['username'],0,1,'utf-8').'*'.mb_substr($row['username'],$usernamelen-1,1,'utf-8');
			}elseif (!empty($row['username'])){
				$tuanranklist[$index]['username']='*'.mb_substr($row['username'],-1,1,'utf-8');
			}
		}

	}
	if ($config['fansrank'] > 0){
	    if ($config['isfansrankshowworker']==1) {

		    $workerlist = db_select ( "SELECT uid FROM " . tablename ( t_worker ) );
		    if (!empty($workerlist)){
		    	$workerkey = " and uid not in (\"" . implode(",",$workerlist) . "\")";
		    }
		    $workerkey = " and uid not in (";
		    foreach ($workerlist as $key => $item) {
		    	if ($key==0){
		    		$workerkey .= $item['uid'];
		    	}else{
		    		$workerkey .="," . $item['uid'];
		    	}
		    }
		    $workerkey .=")";
	    
	    }else{
	    	$workerkey="";
	    }
		$fansranklist = db_select("SELECT * FROM ".tablename(t_fans)."
                            WHERE themeid =" . $themeid . $workerkey ."  ORDER BY tuijian desc,addtime desc limit " . $config['fansrank']);
		foreach ($fansranklist as $index => $row) {
			// $usernamelen=mb_strlen($row['username'],'utf-8');
			// if ($usernamelen > 2){
			// 	$fansranklist[$index]['username']=mb_substr($row['username'],0,1,'utf-8').'*'.mb_substr($row['username'],$usernamelen-1,1,'utf-8');
			// }elseif (!empty($row['username'])){
			// 	$fansranklist[$index]['username']='*'.mb_substr($row['username'],-1,1,'utf-8');
			// }
			$usernamelen=mb_strlen($row['mobile'],'utf-8');
			$fansranklist[$index]['mobilenew']=mb_substr($row['mobile'],0,3,'utf-8').'****'.mb_substr($row['mobile'],$usernamelen-4,4,'utf-8');
		}

	}
	//分享jssdk
	$canshare = 1;
	if($themyrecord['status'] >= 1 && !empty($themyrecord)){
	    if($recordid <= 0){
	        $recordid = $themyrecord['id'];
	    }
	    if (!empty($config['sharetitle2']) && empty($myworker)){
	    	$sharetitle2 = $config['sharetitle2'];
	    }else{
	    	$sharetitle2 = $theme['title'];
	    }
		$sharetitle = str_replace("NICK",$fans['nickname'],$sharetitle2);
		$sharetitle = str_replace("NAME",$themyrecord['username'],$sharetitle);
		if (!empty($shopname)) {
			$sharetitle = str_replace("SHOPNAME",$shopname,$sharetitle);
		}
	}else{
	    if (!empty($config['sharetitle1']) && empty($myworker)){
	    	$sharetitle1 = $config['sharetitle1'];
	    }else{
	    	$sharetitle1 = $theme['title'];
	    }
		$sharetitle = str_replace("NICK",$fans['nickname'],$sharetitle1);
		if (!empty($shopname)) {
			$sharetitle = str_replace("SHOPNAME",$shopname,$sharetitle);
		}
	}
	// if (!empty($theme['jubf']) ){
	// 	$theme['title'] = $theme['jubf'];
	// }
	if (!empty($workername) && $config['isshowkefu']==1){
		$sharetitle = $sharetitle ."【客服:".$workername."】";
	}
	if ($config['iswxshare']==1) {
		$theme['title'] = $sharetitle;
	}
	$sharedesc = $theme['desc'];
	if (empty($theme['img'])){
		$shareimgurl = tomedia($config['headlogo']);
	}else{
		$shareimgurl = tomedia($theme['img']);
	}

	$theme['title'] = Theme::encode($theme['title'],'&#',';');

	$sharedata = array(
	    'themeid'=>$themeid,
	    'fopenid'=>$_G['openid'],
	    'fromuid'=>$_G['member']['uid'],
	    'workerid'=>$workerid,
	);
	if (!empty($recordid)){
		$sharedata['recordid']=$recordid;
	}
	if ($system['friend']==1 || $config['isicon']==3) {
		if (empty($themyrecord)){
			$sharedata['help_uid'] = $help_uid; 
		}
	}
	if (($fans['status']==2 || ($theme['endtime']+$endday) < TIMESTAMP) && $system['s']['isurl']==1) {
		$shareurl =   $_G['siteroot'].createMobileUrl('index',$sharedata);
	}else{
		if (empty($myworker)){
			$shareurl =   $_G['siteroot'].createMobileUrl('index',$sharedata);
		}else{
			$shareurl = str_replace("&recordid=" . $recordid , "",$workerurl);
		}

		if ($system['gongzhong']==1 ){
			$domain3='';
			if ($system['domainpingbi1']==0 && !empty($system['domainhead1'])) {
				$domain3=$system['domainhead1'];
			}elseif ($system['domainpingbi2']==0 && !empty($system['domainhead2'])) {
				$domain3=$system['domainhead2'];
			}elseif ($system['domainpingbi3']==0 && !empty($system['domainhead3'])) {
				$domain3=$system['domainhead3'];
			}
			if (strstr($shareurl,$system['domainhead1'])!==false && $system['domainpingbi1']==1 ){
				$shareurl = str_replace($system['domainhead1'],$domain3,$shareurl);
			}
			if (!empty($system['domainhead2'])) {
				if (strstr($shareurl,$system['domainhead2'])!==false && $system['domainpingbi2']==1 ){
					$shareurl = str_replace($system['domainhead2'],$domain3,$shareurl);
				}
			}
			if ($system['domainpingbi3']==0 && rand(1, 10) < 6){
				$shareurl = str_replace($system['domainhead1'],$system['domainhead3'],$shareurl);
				$shareurl = str_replace($system['domainhead2'],$system['domainhead3'],$shareurl);
			}
		}else{
			if ($system['gongzhong']!=1){
				if (rand(0, 10)<5){
					$shareurl = str_replace($system['s']['domain1'],$system['s']['domain3'],$shareurl);
				}else{
					$shareurl = str_replace($system['s']['domain1'],$system['s']['domain2'],$shareurl);
				}
			}
			if (!empty($system['s']['pingbi01'])) {
				$shareurl = str_replace($system['s']['pingbi01'],$system['s']['domain3'],$shareurl);
			}
			if (!empty($system['s']['pingbi02'])) {
				$shareurl = str_replace($system['s']['pingbi02'],$system['s']['domain3'],$shareurl);
			}
		}
		// if ($system['gongzhong']==1 ){
		// 	$domain3='';
		// 	if ($system['domainpingbi1']==0 && !empty($system['domainhead1'])) {
		// 		$domain3=$system['domainhead1'];
		// 	}elseif ($system['domainpingbi2']==0 && !empty($system['domainhead2'])) {
		// 		$domain3=$system['domainhead2'];
		// 	}elseif ($system['domainpingbi3']==0 && !empty($system['domainhead3'])) {
		// 		$domain3=$system['domainhead3'];
		// 	}
		// 	if (strstr($shareurl,$system['domainhead1'])!==false && $system['domainpingbi1']==1 ){
		// 		$shareurl = str_replace($system['domainhead1'],$domain3,$shareurl);
		// 	}
		// 	if (!empty($system['domainhead2'])) {
		// 		if (strstr($shareurl,$system['domainhead2'])!==false && $system['domainpingbi2']==1 ){
		// 			$shareurl = str_replace($system['domainhead2'],$domain3,$shareurl);
		// 		}
		// 	}
		// 	if ($system['domainpingbi3']==0 && rand(1, 10) < 6){
		// 		$shareurl = str_replace($system['domainhead1'],$system['domainhead3'],$shareurl);
		// 		$shareurl = str_replace($system['domainhead2'],$system['domainhead3'],$shareurl);
		// 	}
		// }else{
		// 	if ($system['gongzhong']!=1 && rand(1, 12) < 5){
		// 		$shareurl = str_replace($system['s']['domain1'],$system['s']['domain3'],$shareurl);
		// 		$shareurl = str_replace($system['s']['domain2'],$system['s']['domain3'],$shareurl);
		// 	}
		// 	if (!empty($system['s']['pingbi01'])) {
		// 		$shareurl = str_replace($system['s']['pingbi01'],$system['s']['domain3'],$shareurl);
		// 	}
		// 	if (!empty($system['s']['pingbi02'])) {
		// 		$shareurl = str_replace($system['s']['pingbi02'],$system['s']['domain3'],$shareurl);
		// 	}
		// }

	}
	$fromuid = $_P['fromuid']; 
	$fopenid = $_P['fopenid'];
    //如果开启了员工海报图
    if (!empty($workerposter)){
        if (count($config['bannerimgs'])<2 && empty($config['bannervideo'])){
            $config['headlogo'] = $workerposter;
        }else{
            array_push($config['bannerimgs'],$workerposter);
        }
    }


	//如果结束了全部打水印
	if ((DOMAIN0 == "30.yixuan.net" || ($theme['endtime']+$endday) < TIMESTAMP || (!empty($theme['jiezhang']) && $theme['status']==2)) && $theme['yixuanbanquan']==0 && empty($theme['USERJISHU'])) {
		$isend = true;
		if($_G['companyname'] =='飞驰软件'){
			$imgright = "/92.jpg";
		}else{
			$imgright = "/91.jpg";
		}
		$config['headlogo']=str_replace("/99.jpg",$imgright,$config['headlogo']);
		$config['content']=str_replace("/99.jpg",$imgright,$config['content']);
		if (!empty($config['imgs'])){
			foreach ($config['imgs'] as $index => $row){
				$config['imgs'][$index]=str_replace("/99.jpg",$imgright,$row);
	        }
        }
        if (!empty($config['centerimgs'])){
			foreach ($config['centerimgs'] as $index => $row){
				$config['centerimgs'][$index]=str_replace("/99.jpg",$imgright,$row);
	        }
	    }
	}
	$bindex=1;
	if ($config['primeprice']!='0.00' && $config['formtextleftopen']!=1){
		$bindex = $bindex + 1;
	}
	
	$member = db_find("SELECT * FROM ".tablename(t_fans)."
			WHERE themeid = :themeid and openid = :openid",$pm);
	
	//纯表单页面跳转
	if ($system['isform']==1 && !empty($config['formimg'])) {
		$sql = "SELECT * FROM " . tablename(t_record) . " where themeid = :themeid and openid = :openid limit 1";
        $recordinfo = db_find($sql, array(":themeid"=>$themeid,":openid"=>$_G['openid']));
        if (empty($recordinfo) || $config['formtourl']==0) {
			$return_clicent = get_defined_vars();
return view('/base/form' , $return_clicent);
			exit;
        }
        if ($config['formtourl']!=$themeid) {		
		    $sharedata = array(
			    'themeid'=>$config['formtourl'],
		        'fromuid'  => $fromuid,
		        'fopenid'  => $fopenid,
		        'workerid'  => $workerid,
			);
			$tourl = $_G['url_scheme'].$_SERVER['HTTP_HOST']."/".createMobileUrl('index',$sharedata);
		
			echo "<script language='javascript' type='text/javascript'>";
			echo "window.location.href='$tourl';"; 
			echo "</script>";  
			exit;
    	}
	}

	if ($system['ruanjian']==1) {
		if($_G['companyname'] =='飞驰软件'){
			$return_clicent = get_defined_vars();
return view('/fcpdd/index' , $return_clicent);
		}else{
			$return_clicent = get_defined_vars();
return view('/weituan/index' , $return_clicent);
		}
	}elseif ($system['ruanjian']==2) {
		if($_G['companyname'] =='飞驰软件'){
			$return_clicent = get_defined_vars();
return view('/fcpdd/index' , $return_clicent);
		}else{
//			$return_clicent = get_defined_vars();
return view('/yx2020/index' , $return_clicent);
            $return_clicent = get_defined_vars();
return view('/fcpdd/index' , $return_clicent);
		}
	}elseif ($system['ruanjian']==3 && $system['softstyle']==2) {
		$return_clicent = get_defined_vars();
return view('/lijianshangjia/index' , $return_clicent);
	}elseif ($system['ruanjian']==3 && $system['softstyle']==4) {
		$return_clicent = get_defined_vars();
return view('/duoshangjia/index' , $return_clicent);
	}elseif ($system['ruanjian']==0 && $system['softstyle']==5) {
		$return_clicent = get_defined_vars();
return view('/jiameng/index' , $return_clicent);
	}elseif ($system['ruanjian']==3 && $system['softstyle']==6) {
		$return_clicent = get_defined_vars();
return view('/lijianduoshangjia/index' , $return_clicent);
	// }elseif ($system['ruanjian']==0 && $system['softstyle']==8) {
	// 	$return_clicent = get_defined_vars();
return view('/woniuwenhua/index' , $return_clicent);
	}elseif($_G['companyname'] =='飞驰软件'){
		$return_clicent = get_defined_vars();
return view('/fcpdd/index' , $return_clicent);
	}else{
		$return_clicent = get_defined_vars();
return view('/yxpdd/pdd' , $return_clicent);
	}

}
}